<template>
  <div class="user-dashboard">
    <div class="dashboard-header">
      <h2>用户运动数据分析</h2>
      <div class="date-picker">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :shortcuts="dateShortcuts"
          @change="onDateRangeChange"
        />
      </div>
    </div>
    
    <el-row :gutter="20" v-loading="loading">
      <!-- 活动概览 -->
      <el-col :span="24">
        <div class="stat-card">
          <h3>活动概览</h3>
          <div class="stat-summary">
            <div class="stat-item" v-for="(stat, index) in activityStats" :key="index">
              <div class="stat-value">{{ stat.value }}</div>
              <div class="stat-label">{{ stat.label }}</div>
            </div>
          </div>
        </div>
      </el-col>
      
      <!-- 活动类型分布 -->
      <el-col :span="12">
        <div class="chart-card">
          <h3>活动类型分布</h3>
          <div class="chart-container" ref="activityTypeChartRef"></div>
        </div>
      </el-col>
      
      <!-- 运动频率 -->
      <el-col :span="12">
        <div class="chart-card">
          <h3>运动频率（近30天）</h3>
          <div class="chart-container" ref="workoutFrequencyChartRef"></div>
        </div>
      </el-col>
      
      <!-- 运动总结 -->
      <el-col :span="24">
        <div class="chart-card">
          <h3>运动总结</h3>
          <div class="chart-container" ref="workoutSummaryChartRef"></div>
        </div>
      </el-col>
      
      <!-- 社交互动 -->
      <el-col :span="24">
        <div class="chart-card">
          <h3>社交互动</h3>
          <div class="chart-container" ref="socialInteractionChartRef"></div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, defineProps, defineEmits } from 'vue';
import * as echarts from 'echarts';
import { 
  getUserStats, 
  getActivityTypeDistribution, 
  getWorkoutFrequency, 
  getWorkoutSummary, 
  getSocialInteractions 
} from '../../api/services';

// Props和事件
const props = defineProps({
  userId: {
    type: [String, Number],
    required: true
  }
});

const emit = defineEmits(['update:loading']);

// 响应式状态
const loading = ref(false);
const dateRange = ref([
  new Date(new Date().setMonth(new Date().getMonth() - 1)),
  new Date()
]);
const activityStats = ref([]);
const activityTypeData = ref([]);
const workoutFrequencyData = ref([]);
const workoutSummaryData = ref({
  dates: [],
  distance: [],
  calories: [],
  duration: []
});
const socialInteractionData = ref({
  dates: [],
  likes: [],
  comments: [],
  shares: []
});

// 图表实例引用
const activityTypeChartRef = ref(null);
const workoutFrequencyChartRef = ref(null);
const workoutSummaryChartRef = ref(null);
const socialInteractionChartRef = ref(null);

// 图表实例
let activityTypeChart = null;
let workoutFrequencyChart = null;
let workoutSummaryChart = null;
let socialInteractionChart = null;

// 日期快捷选项
const dateShortcuts = [
  {
    text: '最近一周',
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
      return [start, end];
    },
  },
  {
    text: '最近一个月',
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setMonth(start.getMonth() - 1);
      return [start, end];
    },
  },
  {
    text: '最近三个月',
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setMonth(start.getMonth() - 3);
      return [start, end];
    },
  },
];

// 格式化日期为YYYY-MM-DD
const formatDate = (date) => {
  const d = new Date(date);
  const year = d.getFullYear();
  const month = String(d.getMonth() + 1).padStart(2, '0');
  const day = String(d.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
};

// 加载用户数据
const loadUserData = async () => {
  if (!props.userId) return;
  
  loading.value = true;
  emit('update:loading', true);
  
  try {
    // 获取日期范围
    const startDate = formatDate(dateRange.value[0]);
    const endDate = formatDate(dateRange.value[1]);
    
    // 并行请求所有数据
    const [
      statsResponse,
      typeDistResponse, 
      frequencyResponse,
      summaryResponse,
      socialResponse
    ] = await Promise.all([
      getUserStats(props.userId, startDate, endDate),
      getActivityTypeDistribution(props.userId, startDate, endDate),
      getWorkoutFrequency(props.userId, startDate, endDate),
      getWorkoutSummary(props.userId, startDate, endDate),
      getSocialInteractions(props.userId, startDate, endDate)
    ]);
    
    // 处理数据
    activityStats.value = statsResponse.data;
    
    // 处理活动类型分布数据，支持两种格式
    if (typeDistResponse.data) {
      if (typeDistResponse.data.typeDistribution) {
        // 如果后端返回的是包含typeDistribution字段的对象
        activityTypeData.value = typeDistResponse.data.typeDistribution;
      } else {
        // 否则直接使用返回的数据
        activityTypeData.value = typeDistResponse.data;
      }
    }
    
    workoutFrequencyData.value = frequencyResponse.data;
    workoutSummaryData.value = summaryResponse.data;
    socialInteractionData.value = socialResponse.data;
    
    // 更新图表
    renderCharts();
  } catch (error) {
    console.error('加载用户数据失败:', error);
  } finally {
    loading.value = false;
    emit('update:loading', false);
  }
};

// 日期范围变化事件
const onDateRangeChange = () => {
  loadUserData();
};

// 初始化图表
const initCharts = () => {
  if (activityTypeChartRef.value) {
    activityTypeChart = echarts.init(activityTypeChartRef.value);
  }
  
  if (workoutFrequencyChartRef.value) {
    workoutFrequencyChart = echarts.init(workoutFrequencyChartRef.value);
  }
  
  if (workoutSummaryChartRef.value) {
    workoutSummaryChart = echarts.init(workoutSummaryChartRef.value);
  }
  
  if (socialInteractionChartRef.value) {
    socialInteractionChart = echarts.init(socialInteractionChartRef.value);
  }
};

// 渲染所有图表
const renderCharts = () => {
  renderActivityTypeChart();
  renderWorkoutFrequencyChart();
  renderWorkoutSummaryChart();
  renderSocialInteractionChart();
};

// 活动类型分布图表
const renderActivityTypeChart = () => {
  if (!activityTypeChart) return;
  
  // 处理typeDistribution对象格式数据
  let typeData = [];
  
  // 如果活动类型数据是数组格式
  if (Array.isArray(activityTypeData.value)) {
    typeData = activityTypeData.value.map(item => ({
      name: item.name,
      value: item.value
    }));
  } 
  // 如果活动类型数据是对象格式 {run: 3, swim: 3, ...}
  else if (typeof activityTypeData.value === 'object' && activityTypeData.value !== null) {
    typeData = Object.entries(activityTypeData.value).map(([type, count]) => ({
      name: type,
      value: count
    }));
  }
  
  // 如果没有数据，直接返回
  if (typeData.length === 0) return;
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'horizontal',
      bottom: 0,
      data: typeData.map(item => item.name)
    },
    series: [
      {
        name: '活动类型',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '18',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: typeData
      }
    ]
  };
  
  activityTypeChart.setOption(option);
};

// 运动频率图表
const renderWorkoutFrequencyChart = () => {
  if (!workoutFrequencyChart || !workoutFrequencyData.value.length) return;
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    xAxis: {
      type: 'category',
      data: workoutFrequencyData.value.map(item => item.date),
      axisLabel: {
        rotate: 45
      }
    },
    yAxis: {
      type: 'value',
      name: '活动次数'
    },
    series: [
      {
        name: '活动次数',
        type: 'bar',
        data: workoutFrequencyData.value.map(item => item.count),
        itemStyle: {
          color: '#91cc75'
        }

      }
    ],
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',
      containLabel: true
    }
  };
  
  workoutFrequencyChart.setOption(option);
};

// 运动总结图表
const renderWorkoutSummaryChart = () => {
  if (!workoutSummaryChart || !workoutSummaryData.value.dates) return;
  
  const { dates, distance, calories, duration } = workoutSummaryData.value;
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross'
      }
    },
    legend: {
      data: ['距离(km)', '卡路里(kcal)', '时长(min)']
    },
    xAxis: {
      type: 'category',
      data: dates,
      axisLabel: {
        rotate: 45
      }
    },
    yAxis: [
      {
        type: 'value',
        name: '距离(km)',
        position: 'left'
      },
      {
        type: 'value',
        name: '卡路里(kcal)',
        position: 'right'
      }
    ],
    series: [
      {
        name: '距离(km)',
        type: 'line',
        data: distance,
        yAxisIndex: 0,
        smooth: true
      },
      {
        name: '卡路里(kcal)',
        type: 'line',
        data: calories,
        yAxisIndex: 1,
        smooth: true
      },
      {
        name: '时长(min)',
        type: 'bar',
        data: duration,
        yAxisIndex: 0
      }
    ],
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',
      containLabel: true
    }
  };
  
  workoutSummaryChart.setOption(option);
};

// 社交互动图表
const renderSocialInteractionChart = () => {
  if (!socialInteractionChart || !socialInteractionData.value.dates) return;
  
  const { dates, likes, comments, shares } = socialInteractionData.value;
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        label: {
          backgroundColor: '#6a7985'
        }
      }
    },
    legend: {
      data: ['点赞', '评论', '分享']
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: dates,
      axisLabel: {
        rotate: 45
      }
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '点赞',
        type: 'line',
        stack: '总量',
        areaStyle: {},
        emphasis: {
          focus: 'series'
        },
        data: likes
      },
      {
        name: '评论',
        type: 'line',
        stack: '总量',
        areaStyle: {},
        emphasis: {
          focus: 'series'
        },
        data: comments
      },
      {
        name: '分享',
        type: 'line',
        stack: '总量',
        areaStyle: {},
        emphasis: {
          focus: 'series'
        },
        data: shares
      }
    ],
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',
      containLabel: true
    }
  };
  
  socialInteractionChart.setOption(option);
};

// 监听窗口大小变化，重新调整图表大小
const handleResize = () => {
  activityTypeChart?.resize();
  workoutFrequencyChart?.resize();
  workoutSummaryChart?.resize();
  socialInteractionChart?.resize();
};

// 监听用户ID变化
watch(() => props.userId, (newVal) => {
  if (newVal) {
    loadUserData();
  }
});

// 组件挂载
onMounted(() => {
  initCharts();
  loadUserData();
  window.addEventListener('resize', handleResize);
});

// 组件卸载
const onUnmounted = () => {
  window.removeEventListener('resize', handleResize);
  activityTypeChart?.dispose();
  workoutFrequencyChart?.dispose();
  workoutSummaryChart?.dispose();
  socialInteractionChart?.dispose();
};
</script>

<style scoped>
.user-dashboard {
  padding: 20px;
}

.dashboard-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.stat-card,
.chart-card {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 20px;
  margin-bottom: 20px;
}

.stat-summary {
  display: flex;
  justify-content: space-around;
  flex-wrap: wrap;
}

.stat-item {
  text-align: center;
  padding: 15px;
}

.stat-value {
  font-size: 28px;
  font-weight: bold;
  color: #409EFF;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  color: #606266;
}

.chart-container {
  height: 350px;
}
</style> 
